package model;

import helper.Configuration;
import helper.HttpHandler;
import helper.KXmlParser;
import helper.Library;

import java.util.Hashtable;

public class GeoCoder
{

	private Hashtable config;
	private HttpHandler hh;
	
	public GeoCoder()
	{
		Configuration configuration = new Configuration();
		this.config = configuration.loadConfiguration();
		this.hh = new HttpHandler();
	}
	
	public String getCoordinates(String address) throws Exception
	{
		if(address == null || address.trim().length() < 1)
			throw new Exception();
	
		String url = buildGet(address,"xml");
		String answer = this.hh.httpGet(url);
		KXmlParser kxml = new KXmlParser();
		kxml.parseXml(answer);
	
		Library lib = new Library();
		String coordinates = kxml.getCoordinates();
		String tokens[] = lib.split(",", coordinates);
		
		System.out.println("coordinates: " + coordinates);
		System.out.println("Tamanho: " + tokens.length);
		
		if(tokens.length != 3)
			throw new Exception();
		
		return tokens[1]+","+tokens[0];
		       
	}
	
	public String buildGet(String q, String output)
	{
		Library lib = new Library();
		String url = this.config.get("geoapiurl").toString();
		url += "?q="+lib.urlEncode(q);
		url += "&output="+output;
		url += "&sensor=false";
		url += "&key="+this.config.get("apikey");
		
		return url;
	}
}
